package com.zoe.onelink.core.exception.handler;

import com.zoe.onelink.common.constant.OnelinkConstant;
import com.zoe.onelink.common.enumeration.ExceptionCodeEnum;
import com.zoe.onelink.core.exception.constant.ErrorControllerConstant;
import com.zoe.onelink.core.util.LocaleResolverUtil;
import com.zoe.onelink.util.StrUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController;
import org.springframework.boot.autoconfigure.web.servlet.error.ErrorViewResolver;
import org.springframework.boot.web.servlet.error.ErrorAttributes;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

public class OnelinkBasicErrorController extends BasicErrorController {

    @Value("${spring.application.name:unknown}")
    private String appName;

    public OnelinkBasicErrorController(ErrorAttributes errorAttributes, ErrorProperties errorProperties, List<ErrorViewResolver> errorViewResolvers) {
        super(errorAttributes, errorProperties, errorViewResolvers);
    }

    @Override
    public ResponseEntity<Map<String, Object>> error(HttpServletRequest request) {
        HttpStatus status = getStatus(request);
        if (status == HttpStatus.NO_CONTENT) {
            return new ResponseEntity<>(status);
        }
        Map<String, Object> body = getErrorAttributes(request, getErrorAttributeOptions(request, MediaType.ALL));
        if (body == null) {
            return new ResponseEntity<>(null, status);
        }
        body.put(ErrorControllerConstant.STATUS, body.get(ErrorControllerConstant.STATUS));
        if (status == HttpStatus.NOT_FOUND) {
            String message = LocaleResolverUtil.getMessage(ExceptionCodeEnum.API_NOT_FOUND);
            body.put(ErrorControllerConstant.MESSAGE, message);
            body.put(ErrorControllerConstant.ERROR, "Api not found");
        } else if (Boolean.TRUE.equals(request.getAttribute(OnelinkConstant.ATTR_TOKEN_NOT_NULL))) {
            body.put(ErrorControllerConstant.MESSAGE, LocaleResolverUtil.getMessage(ExceptionCodeEnum.TOKEN_NOT_NULL));
            body.put(ErrorControllerConstant.ERROR, "Api might not found");
        }
        String error = StrUtil.format("[{}] {} Path: {}", this.appName, body.get(ErrorControllerConstant.ERROR), body.get(ErrorControllerConstant.PATH));
        body.put(ErrorControllerConstant.DATA, null);
        body.put(ErrorControllerConstant.ERROR, error);
        body.remove(ErrorControllerConstant.STATUS);
        body.remove(ErrorControllerConstant.PATH);
        body.remove(ErrorControllerConstant.TIMESTAMP);
        return new ResponseEntity<>(body, status);
    }
}